<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: create by allen.qiang
// +----------------------------------------------------------------------

/**
 * 商品生产信息
 * @package  htdocs
 * @subpackage  quanliadmin
 * @author   create by allen.qiang
 * @version 1.0
 */

class goodsProduce {

    private $dbca;

    public function __construct( $dbca ) {
        $this->dbca = $dbca;
    }
    
    
    /**
     * 商品生产信息列表
     */
    public function goodsProduces(&$arg_array) {
    	//sql字符串
    	$sql = '';
    	
    	//参数类型字符串
    	$params_type = '';
    	
    	//参数值数组
    	$params_array = array();
    	
    	//基本信息ID
    	if (isset($arg_array['pid']) && is_numeric($arg_array['pid'])) {
    		$sql .= ' AND pid = ?';
    		$params_type .= 'i';
    		$params_array[] = $arg_array['pid'];
    	}
    	
    	//基本信息组ID
    	if (isset($arg_array['pGroupID']) && is_numeric($arg_array['pGroupID'])) {
    		$sql .= ' AND pGroupID = ?';
    		$params_type .= 'i';
    		$params_array[] = $arg_array['pGroupID'];
    	}
    	
    	//基本信息值
    	if (isset($arg_array['pName']) && !empty($arg_array['pName'])) {
    		$sql .= ' AND pName LIKE ?';
    		$params_type .= 's';
    		$params_array[] = $arg_array['pName'];
    	}
    	
    	//维度中文
    	if (isset($arg_array['pGroupName']) && trim($arg_array['pGroupName']) != '') {
    		$sql .= ' AND pGroupName LIKE ?';
    		$params_type .= 's';
    		$params_array[] = '%' . trim($arg_array['pGroupName']) . '%';
    	}
    	
    	//使用标志
    	if (isset($arg_array['useFlg']) && is_numeric($arg_array['useFlg']) && in_array($arg_array['useFlg'],array(0,1))) {
    		$sql .= ' AND useFlg = ?';
    		$params_type .= 'i';
    		$params_array[] = $arg_array['useFlg'];
    	}
    	
    	//扩展
    	if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
    		$sql .= $arg_array['extend'];
    	}
    	
    	if ($sql) {
    		$sql = ' WHERE ' . substr($sql, 4);
    	}
    	
    	try {
    	
    		if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {
    	
    			//统计促销行数
    			$search_sql  = 'SELECT COUNT(*) AS count FROM goods_produce ' . $sql;
    			$count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
    			$item_count  = $count_array[0]->count;
    			if ($item_count == 0) {
    				$arg_array['count'] = 0;
    				return null;
    			}
    	
    			$arg_array['count'] = $item_count;
    	
    			//排序
    			if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
    				$sql .= sprintf(' ORDER BY goods_produce.%s %s', $arg_array['sortname'], $arg_array['sortorder']);
    	
    			//分页
    			if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
    				$arg_array['page'] = 1;
    	
    			$sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);
    	
    		} else {
    	
    			$arg_array['count'] = 0;
    	
    			//排序
    			if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
    				$sql .= sprintf(' ORDER BY goods_produce.%s %s', $arg_array['sortname'], $arg_array['sortorder']);
    	
    		}
    	
    		//查询商品促销信息
    	
    		$search_sql = 'SELECT pid,pName,pGroupID,pGroupName,sortOrder,useFlg FROM goods_produce' . $sql;
    		$temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
    	
    		if ($temp_item_array) {
    			foreach($temp_item_array as &$item) {
    				$item_array[] = array(
						'pid' 	    	=> $item->pid,
						'pName' 		=> $item->pName,
						'pGroupID' 		=> $item->pGroupID,
						'pGroupName' 	=> $item->pGroupName,
						'sortOrder'     => $item->sortOrder,
						'useFlg' 	    => $item->useFlg
    				);
    			}
    		}
    	
    		return isset($item_array) ? $item_array : null;
    	
    	} catch (Exception $e) {
    	
    		error_log($e->getMessage());
    		return null;
    	
    	}
    }
    
    /**
     * 商品生产信息组列表
     */
    public function goodsProduceGroup(&$arg_array) {
    	
    	//sql字符串
    	$sql = '';
    	
    	//参数类型字符串
    	$params_type = '';
    	
    	//参数值数组
    	$params_array = array();
    	
    	//基本信息组ID
    	if (isset($arg_array['pGroupID']) && is_numeric($arg_array['pGroupID'])) {
    		$sql .= ' AND pGroupID = ?';
    		$params_type .= 'i';
    		$params_array[] = $arg_array['pGroupID'];
    	}
    	
    	//维度中文
    	if (isset($arg_array['pGroupName']) && trim($arg_array['pGroupName']) != '') {
    		$sql .= ' AND pGroupName LIKE ?';
    		$params_type .= 's';
    		$params_array[] = '%' . trim($arg_array['pGroupName']) . '%';
    	}
    	
    	//使用标志
    	if (isset($arg_array['useFlg']) && is_numeric($arg_array['useFlg']) && in_array($arg_array['useFlg'],array(0,1))) {
    		$sql .= ' AND useFlg = ?';
    		$params_type .= 'i';
    		$params_array[] = $arg_array['useFlg'];
    	}
    	
    	//扩展
    	if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
    		$sql .= $arg_array['extend'];
    	}
    	
    	if ($sql) {
    		$sql = ' WHERE ' . substr($sql, 4);
    	}
    	
    	try {
    	
    		if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {
    	
    			//统计行数
    			$search_sql  = 'SELECT COUNT(*) AS count FROM goods_produce_group ' . $sql;
    			$count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
    			$item_count  = $count_array[0]->count;
    			if ($item_count == 0) {
    				$arg_array['count'] = 0;
    				return null;
    			}
    	
    			$arg_array['count'] = $item_count;
    	
    			//排序
    			if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
    				$sql .= sprintf(' ORDER BY goods_produce_group.%s %s', $arg_array['sortname'], $arg_array['sortorder']);
    	
    			//分页
    			if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
    				$arg_array['page'] = 1;
    	
    			$sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);
    	
    		} else {
    	
    			$arg_array['count'] = 0;
    	
    			//排序
    			if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
    				$sql .= sprintf(' ORDER BY goods_produce_group.%s %s', $arg_array['sortname'], $arg_array['sortorder']);
    	
    		}
    	
    		//查询商品基本信息
    	
    		$search_sql = 'SELECT pGroupID,pGroupName,sortOrder,useFlg FROM goods_produce_group' . $sql;
    		$temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
    	
    		if ($temp_item_array) {
    			foreach($temp_item_array as &$item) {
    	
    				//根据商品生产信息组ID，查找商品生产信息
    				$goods_produce_array = array(
    						'pGroupID' 	=> $item->pGroupID
    				);
    	
    				$goods_produce = $this->goodsProduces($goods_produce_array);
    	
    				$item_array[] = array(
    						'pGroupID' 			=> $item->pGroupID,
    						'pGroupName' 		=> $item->pGroupName,
    						'sortOrder'     	=> $item->sortOrder,
    						'useFlg' 	   		=> $item->useFlg,
    						'goods_produce'   	=> $goods_produce
    				);
    			}
    		}
    	
    		return isset($item_array) ? $item_array : null;
    	
    	} catch (Exception $e) {
    	
    		error_log($e->getMessage());
    		return null;
    	
    	}    	
    }
    
    /**
     * 获取添加时的最大序号
     */
	public function getmaxSort() {
		
		$maxsort = $this->dbca->stmt_query('SELECT MAX(sortOrder) AS maxsort FROM goods_produce_group');
		
		$maxsort = $maxsort[0]->maxsort;
		
		return $maxsort;
		
	}
    
    /**
     * 商品生产信息添加和修改
     */
	public function savegoodsProduce($arg_array) {
        global $G_PGLOB;

		/**
		 * 检测参数
		 */
		//定义错误变量
		$error_msg = '';
		
		if (isset($arg_array['pGroupID']) && is_numeric($arg_array['pGroupID']) && $arg_array['pGroupID'] > 0) {
			$pGroupID = $arg_array['pGroupID'];			
		} else {
			$pGroupID = 0;
		}
		
		if (isset($arg_array['pGroupName']) && !empty($arg_array['pGroupName'])) {
			$pGroupName = $arg_array['pGroupName'];
		} else {
			$error_msg .= '未输入维度中文<br />';
		}
		
		if (isset($arg_array['sortOrder']) && is_numeric($arg_array['sortOrder']) > 0) {
			$sortOrder = $arg_array['sortOrder'];
		} else {
			$error_msg .= '排序序号不正确<br />';
		}
		
		if (isset($arg_array['produce_array']) && is_array($arg_array['produce_array']) && !empty($arg_array['produce_array'])) {
			$produce_array = $arg_array['produce_array'];
		} else {
			$error_msg .= '未输入基本信息<br />';
		}

        foreach($produce_array as $v) {
            if (empty($v)) {
                $error_msg .= '基本生产信息有未添加的<br />';
                break;
            }
        }

        //判断数组是否存在重复
        if (count($produce_array) != count(array_unique($produce_array))) {
            return array( 'code' => 400 , 'message' => '商品生产基本信息值存在重复' );
        }
		
		$use_array = $arg_array['use_array'];
		
		if ($error_msg != '') {
			return array( 'code' => 400 , 'message' => $error_msg );
		}
		
		/**
		 * 存入数据库
		 */
        //添加和修改的标志
        $flg = 0;

        //商品生产信息组表
        $goods_produce_group = new entity('goods_produce_group');

        if ($pGroupID > 0) {

            $goods_produce_group->pGroupID = $pGroupID;
            if (!$this->dbca->fetch($goods_produce_group)) {
                return array( 'code' => 404 , 'message' => '修改的商品生产信息不存在' );
            }

            $goods_produce_group->editor = $G_PGLOB->currentUserID;
            $allsortOrder = $this->dbca->stmt_query('SELECT sortOrder,pGroupName FROM goods_produce_group WHERE pGroupID != ?','i',$pGroupID);

            //获得当前生产信息组的所有生产信息名称
            $pNameInfo = $this->dbca->stmt_query('SELECT pName FROM goods_produce WHERE pGroupID = ?','i',$pGroupID);

            $flg = 1;
        } else {
            $goods_produce_group->creator = $G_PGLOB->currentUserID;
            $allsortOrder = $this->dbca->stmt_query('SELECT sortOrder,pGroupName FROM goods_produce_group');
        }

        $msg = '';
        foreach ($allsortOrder as $value) {
            if ($value->sortOrder == $sortOrder) {
                $msg.= '排序序号已存在<br />';
            }
            if ($value->pGroupName == $pGroupName) {
                $msg .= '维度中文已存在<br />';
            }
        }

        if (!empty($msg)) {
            return array( 'code' => 400 , 'message' => $msg );
        }

        $goods_produce_group->pGroupName = $pGroupName;
        $goods_produce_group->useFlg = 1;
        $goods_produce_group->sortOrder = $sortOrder;

		try {
			$this->dbca->beginTransaction();

			if (!$this->dbca->save($goods_produce_group)) {
				throw new Exception('商品生产信息组保存失败', 400);
			}
			
			if ($pGroupID == 0) {
				$pGroupID = $this->dbca->insert_id;
			}

            if (isset($pNameInfo) && !empty($pNameInfo)) {
                foreach($pNameInfo as $v) {
                    $pName = $v->pName;
                    if (in_array($pName,$produce_array)) {
                        $goods_produce = new entity('goods_produce');
                        $goods_produce->pGroupID = $pGroupID;
                        $goods_produce->pName = $pName;
                        if (!$this->dbca->fetch($goods_produce)) {
                            throw new Exception( '没有此基本生产信息' , 404 );
                        }
                        $k = array_search($pName,$produce_array);
                        $goods_produce->pGroupName  = $pGroupName;
                        $goods_produce->useFlg      = $use_array[$k];

                        $this->dbca->save($goods_produce);

                        //将当前基本生产信息删除
                        unset($produce_array[$k]);
                        unset($use_array[$k]);

                    } else {
                        $this->dbca->stmt_query('DELETE FROM goods_produce WHERE pGroupID = ? AND pName = ?','is',array($pGroupID,$pName));
                    }
                }
            }

            //获取商品基本信息的序号
            $produce_order = $this->dbca->stmt_query('SELECT IF(MAX(sortOrder) IS NULL ,1,MAX(sortOrder)+1) AS produce_order FROM goods_produce');
            $produce_order = $produce_order[0]->produce_order;
			
			//商品生产信息表
			foreach ($produce_array as $k=>$v) {
                foreach ($use_array as $k1=>$v1) {
                    if ($k == $k1) {
                        $goods_produce = new entity('goods_produce');
                        $goods_produce->creator = $G_PGLOB->currentUserID;
                        $goods_produce->pName = $v;
                        $goods_produce->useFlg = $v1;
                        $goods_produce->pGroupID = $pGroupID;
                        $goods_produce->pGroupName = $pGroupName;
                        $goods_produce->sortOrder = $produce_order;

                        if (!$this->dbca->save($goods_produce)) {
                            throw new Exception('商品生产信息保存失败', 400);
                        }

                        $produce_order++;
                    }
                }

			}
			
			$this->dbca->commit();
			return array( 'code' => 200 , 'message' => 'ok' , 'data' => $flg );
			
		} catch (Exception $e) {
			$this->dbca->rollback();

			if ($e->getCode() > 0) {
				return array( 'code' => $e->getCode() , 'message' => $e->getMessage() );
			} else {
				return array( 'code' => 500 , 'message' => '系统错误' );
			}
		}
	}
	
	/**
	 * 商品生产信息的删除
	 */
	public function delgoodsProduce($pGroupID) {
		try{
		
			$this->dbca->beginTransaction();
		
			$goods_produce_group = new entity('goods_produce_group');
			$goods_produce_group->pGroupID = $pGroupID;
			if (!$this->dbca->fetch($goods_produce_group)) {
				throw new Exception('要删除的商品生产信息不存在',404);
			} else {
				if (!$this->dbca->delete($goods_produce_group)) {
					throw new Exception('删除商品生产信息失败',400);
				}
			}
		
			if (!$this->dbca->stmt_query('DELETE FROM goods_produce WHERE pGroupID = ?','i',$pGroupID)) {
				throw new Exception('删除基本信息值失败',400);
			}
		
			$this->dbca->commit();
		
			return array( 'code' => 200 , 'message' => '数据删除成功' );
		
		} catch (Exception $e) {
		
			$this->dbca->rollback();
		
			if ($e->getCode() > 0) {
				return array( 'code' => $e->getCode() , 'message' => $e->getMessage() );
			} else {
				return array( 'code' => 500 , 'message' => '系统错误' );
			}
		
		}
		
	}
	
	/**
	 * 商品生产信息的使用标志修改
	 */
	public function changegoodsProduce($pGroupID,$useFlg) {
		try{
		
			//检测参数
			$goods_produce_group = new entity('goods_produce_group');
			$goods_produce_group->pGroupID = $pGroupID;
			if (!$this->dbca->fetch($goods_produce_group)) {
				throw new Exception( '查无此商品维度信息' , 404 );
			}
		
			if (!is_numeric($useFlg) || !in_array($useFlg,array(0,1))) {
				throw new Exception( '使用状态不正确' , 404 );
			}
		
			//多页面操作问题
			if ($useFlg == 1 && $goods_produce_group->useFlg == 1) {
				throw new Exception( '商品维度已经启用,请刷新页面' , 400 );
			}
		
			if ($useFlg == 0 && $goods_produce_group->useFlg == 0) {
				throw new Exception( '商品维度已经禁用,请刷新页面' , 400 );
			}
		
			//使用状态修改
			$goods_produce_group->useFlg = $useFlg;
		
			if (!$this->dbca->save($goods_produce_group)) {
				throw new Exception( '使用状态修改失败' , 400 );
			}
		
			return array( 'code' => 200 , 'message' => 'ok' );
		
		} catch (Exception $e) {
		
			if ($e->getCode() > 0) {
				return array( 'code' => $e->getCode() , 'message' => $e->getMessage() );
			} else {
				return array( 'code' => 500 , 'message' => '系统错误' );
			}
		
		}
	}
	
	/**
	 * 批量添加生产信息
	 *
	 * @param unknown_type $arg_array
	 */
	public function searchProduct( &$arg_array ){
		
		//检验参数
    	if (!isset($arg_array['params']) || empty($arg_array['params'])) {
    		return array('code' => 400, 'message' => '参数错误');
    	}
    	
    	$group_str = '';
    	$product_array = array(
    		'useFlg' => 1
    	);

    	foreach ($arg_array['params'] as $p) {
    		$group_str .= $p . ',';
    	}
    	if (!empty($group_str)) {
			$group_str = substr($group_str, 0, -1);
			$product_array['extend'] = " AND pGroupID IN ($group_str) ORDER BY pGroupID ASC,sortOrder ASC";
    	} else {
    		return array('code' => 400, 'message' => '生产信息未找到');
    	}
    	
    	$product_result = $this->goodsProduces( $product_array );
    	if (!$product_result) {
    		return array('code' => 400, 'message' => '生产信息未找到');
    	}

    	return array('code' => 200, 'data' => $product_result);

    }
    
    /**
     * 查询商品生产信息映射
     */
    public function searchGoodsProducesRelation(&$arg_array) {
    	//sql字符串
    	$sql = '';
    	
    	//参数类型字符串
    	$params_type = '';
    	
    	//参数值数组
    	$params_array = array();
    	
    	//商品网购号
    	if (isset($arg_array['postID']) && is_numeric($arg_array['postID'])) {
    		$sql .= ' AND postID = ?';
    		$params_type .= 'i';
    		$params_array[] = $arg_array['postID'];
    	}
    
    	//扩展
    	if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
    		$sql .= $arg_array['extend'];
    	}
    	
    	if ($sql) {
    		$sql = ' WHERE ' . substr($sql, 4);
    	}
    	
    	try {
    	
    		if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {
    	
    			//统计促销行数
    			$search_sql  = 'SELECT COUNT(*) AS count FROM goods_produce_relation ' . $sql;
    			$count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
    			$item_count  = $count_array[0]->count;
    			if ($item_count == 0) {
    				$arg_array['count'] = 0;
    				return null;
    			}
    	
    			$arg_array['count'] = $item_count;
    	
    			//排序
    			if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
    				$sql .= sprintf(' ORDER BY goods_produce.%s %s', $arg_array['sortname'], $arg_array['sortorder']);
    	
    			//分页
    			if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
    				$arg_array['page'] = 1;
    	
    			$sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);
    	
    		} else {
    	
    			$arg_array['count'] = 0;
    	
    			//排序
    			if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
    				$sql .= sprintf(' ORDER BY goods_produce.%s %s', $arg_array['sortname'], $arg_array['sortorder']);
    	
    		}
    	
    		//查询商品促销信息
    	
    		$search_sql = 'SELECT * FROM goods_produce_relation' . $sql;
    		$temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
    	
    		if ($temp_item_array) {
    			foreach($temp_item_array as &$item) {
    				$item_array[] = array(
						'postID'	=> $item->postID,
						'pGroupID'	=> $item->pGroupID,
						'pGroupName'	=> $item->pGroupName,
						'pid'	=> $item->pid,
						'pName'	=> $item->pName
    				);
    			}
    		}
    	
    		return isset($item_array) ? $item_array : null;
    	
    	} catch (Exception $e) {
    	
    		error_log($e->getMessage());
    		return null;
    	
    	}
    }
    
}